package com.hiof.servercommunication.background.job;

import com.hiof.utility.Utility;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by IntelliJ IDEA.
 * User: manish
 * Date: 4/1/12
 * Time: 12:50 PM
 * To change this template use File | Settings | File Templates.
 */
public class JobThreadQueue implements Runnable {

    private static JobThreadQueue instance;
    private static LinkedBlockingQueue<AbstractJob> jobQueue = new LinkedBlockingQueue<AbstractJob>();
    private static boolean isAlive = false;
    private Thread jobThread;

    public static JobThreadQueue getInstance() {
        if (instance == null) {
            instance = new JobThreadQueue();
        }
        return instance;
    }

    private JobThreadQueue() {

    }

    public void startThread() {
        if (!isAlive) {
            isAlive = true;
            jobThread = new Thread(this);
            jobThread.start();
        }
    }

    public void stopThread() {
        isAlive = false;
    }

    public void addJob(AbstractJob job) {
        jobQueue.add(job);
    }

    private String processJob(AbstractJob job) {
        job.executeJob();
        return "ok";
    }

    @SuppressWarnings("SleepWhileInLoop")
    @Override
    public void run() {
        Utility.debug(this.getClass().toString(), "isAlive:" + isAlive + " jobsize:" + jobQueue.size());
        while(isAlive) {
            Utility.debug(this.getClass().toString(), "jobsize:" + jobQueue.size());
            if (jobQueue.size() > 0) {
                AbstractJob job = jobQueue.poll();
                if (job != null) {
                    processJob(job);
                }
            } else {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
//                    TODO handle error
                    Utility.error(this.getClass().toString(), e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }

    public void clearJobQueue() {
        jobQueue.clear();
    }

    class JobThread implements Runnable {
        AbstractJob job;

        JobThread(AbstractJob job1) {
            job = job1;
        }

        @Override
        public void run() {
            processJob(job);
        }
    }

}
